<template>
  <s-clean-layout :title="isEdit ? '编辑联系人' : '添加联系人'" navbar="normal">
    <!-- 表单内容 -->
    <scroll-view scroll-y class="form-container">
      <!-- 头像 -->
      <view class="form-section">
        <view class="form-item avatar-item">
          <text class="item-label">头像</text>
          <view class="avatar-wrapper" @tap="uploadAvatar">
            <image class="avatar-image" :src="formData.avatarUrl || '/static/images/default-avatar.png'" mode="aspectFill"></image>
            <view class="avatar-upload-mask">
              <text class="upload-icon">+</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 基本信息 -->
      <view class="form-section">
        <view class="form-item">
          <text class="item-label">姓名</text>
          <input class="item-input" v-model="formData.name" placeholder="请输入" />
        </view>
        
        <view class="form-item">
          <text class="item-label">昵称</text>
          <input class="item-input" v-model="formData.nickname" placeholder="请输入" />
        </view>
        
        <view class="form-item">
          <text class="item-label">性别</text>
          <picker class="item-picker" :range="genderOptions" @change="onGenderChange">
            <view class="picker-value">
              <text :class="{ 'placeholder-text': !genderOptions[formData.gender] || formData.gender === 0 }">
                {{ genderOptions[formData.gender] || '无' }}
              </text>
              <text class="arrow-icon">›</text>
            </view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="item-label">现居城市</text>
          <input class="item-input" v-model="formData.homeAddress" placeholder="请输入" />
        </view>
        
        <view class="form-item tag-header" @tap="selectRelationship">
          <text class="item-label">与我的关系</text>
          <view class="item-right">
            <view v-if="!formData.relationshipName" class="placeholder-text">无</view>
            <view v-else class="tag-container">
              <view class="type-tag">
                {{ formData.relationshipName }}
              </view>
            </view>
            <text class="arrow-icon">›</text>
          </view>
        </view>
      </view>
      
      <!-- 联系方式 -->
      <view class="form-section">
        <view class="section-title">联系方式</view>
        
        <view class="form-item">
          <text class="item-label">手机号码1</text>
          <input class="item-input" v-model="formData.phoneNumber" placeholder="请输入手机号码" />
        </view>
        
        <view class="form-item">
          <text class="item-label">手机号码2</text>
          <input class="item-input" v-model="formData.phoneNumber2" placeholder="请输入手机号码" />
        </view>
      </view>
      
      <!-- 展开更多按钮 -->
      <view class="expand-button" :class="{ 'expanded': expanded }" @tap="toggleExpand">
        <text>{{ expanded ? '收起' : '展开更多' }}</text>
      </view>
      
      <!-- 更多信息（可展开收起） -->
      <view v-if="expanded">
        <!-- 出生信息 -->
        <view class="form-section">
          <view class="form-item">
            <text class="item-label">出生日期</text>
            <picker class="item-picker" mode="date" :value="formData.birthday" @change="onBirthdayChange">
              <view class="picker-value">
                <text :class="{ 'placeholder-text': !formData.birthday }">
                  {{ formData.birthday || '请选择' }}
                </text>
                <text class="arrow-icon">›</text>
              </view>
            </picker>
          </view>
          
        </view>
        
        <!-- 爱好 -->
        <view class="form-section">
          <view class="form-item tag-header" @tap="showTagSelect('LIKE')">
            <text class="item-label">爱好</text>
            <view class="item-right">
              <view v-if="getSelectedTags('LIKE').length === 0" class="placeholder-text">无</view>
              <view v-else class="tag-container">
                <view 
                  v-for="(tag, index) in getSelectedTags('LIKE')" 
                  :key="index" 
                  class="tag-item"
                  :style="{ backgroundColor: tag.color }"
                >
                  {{ tag.tagName }}
                </view>
              </view>
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </view>
        
        <!-- 讨厌 -->
        <view class="form-section">
          <view class="form-item tag-header" @tap="showTagSelect('NOTLIKE')">
            <text class="item-label">讨厌</text>
            <view class="item-right">
              <view v-if="getSelectedTags('NOTLIKE').length === 0" class="placeholder-text">无</view>
              <view v-else class="tag-container">
                <view 
                  v-for="(tag, index) in getSelectedTags('NOTLIKE')" 
                  :key="index" 
                  class="tag-item"
                  :style="{ backgroundColor: tag.color }"
                >
                  {{ tag.tagName }}
                </view>
              </view>
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </view>
        
        <!-- 口味 -->
        <view class="form-section">
          <view class="form-item tag-header" @tap="showTagSelect('EAT')">
            <text class="item-label">口味</text>
            <view class="item-right">
              <view v-if="getSelectedTags('EAT').length === 0" class="placeholder-text">无</view>
              <view v-else class="tag-container">
                <view 
                  v-for="(tag, index) in getSelectedTags('EAT')" 
                  :key="index" 
                  class="tag-item"
                  :style="{ backgroundColor: tag.color }"
                >
                  {{ tag.tagName }}
                </view>
              </view>
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </view>
        
        <!-- 习惯 -->
        <view class="form-section">
          <view class="form-item tag-header" @tap="showTagSelect('HABIT')">
            <text class="item-label">习惯</text>
            <view class="item-right">
              <view v-if="getSelectedTags('HABIT').length === 0" class="placeholder-text">无</view>
              <view v-else class="tag-container">
                <view 
                  v-for="(tag, index) in getSelectedTags('HABIT')" 
                  :key="index" 
                  class="tag-item"
                  :style="{ backgroundColor: tag.color }"
                >
                  {{ tag.tagName }}
                </view>
              </view>
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </view>
        
        <!-- 学校 -->
        <view class="form-section">
          <view class="form-item">
            <text class="item-label">学校</text>
            <input class="item-input" v-model="formData.school" placeholder="请输入" />
          </view>
        </view>
        
        <!-- 职业 -->
        <view class="form-section">
          <view class="form-item">
            <text class="item-label">职业</text>
            <input class="item-input" v-model="formData.work" placeholder="请输入" />
          </view>
        </view>
        
        <!-- 公司 -->
        <view class="form-section">
          <view class="form-item">
            <text class="item-label">公司</text>
            <input class="item-input" v-model="formData.companyName" placeholder="请输入" />
          </view>
        </view>
        
        <!-- 专业技能 -->
        <view class="form-section">
          <view class="form-item tag-header" @tap="showTagSelect('SKILL')">
            <text class="item-label">专业技能</text>
            <view class="item-right">
              <view v-if="getSelectedTags('SKILL').length === 0" class="placeholder-text">无</view>
              <view v-else class="tag-container">
                <view 
                  v-for="(tag, index) in getSelectedTags('SKILL')" 
                  :key="index" 
                  class="tag-item"
                  :style="{ backgroundColor: tag.color }"
                >
                  {{ tag.tagName }}
                </view>
              </view>
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </view>
        
        <!-- 邮寄地址 -->
        <view class="form-section">
          <view class="form-item">
            <text class="item-label">邮寄地址</text>
            <input class="item-input" v-model="formData.mailingAddress" placeholder="请输入" />
          </view>
        </view>
        
        <!-- 备注 -->
        <view class="form-section">
          <view class="form-item">
            <textarea class="item-textarea" v-model="formData.remark" placeholder="添加备注" />
          </view>
        </view>
      </view>
      
      <!-- 底部间距，确保内容不被底部保存按钮遮挡 -->
      <view style="height: 120rpx;"></view>
    </scroll-view>
    
    <!-- 底部保存按钮 -->
    <view class="bottom-save-button" @tap="saveContact">
      <text>保存</text>
    </view>
  </s-clean-layout>
</template>

<script>
import ContactApi from '@/sheep/api/contact/contact';
import TagApi from '@/sheep/api/tag/tag';
import FileApi from '@/sheep/api/infra/file';

export default {
  // 修改 data 中的 formData 结构
  data() {
    return {
      statusBarHeight: 20,
      isEdit: false,
      contactId: null,
      expanded: false, // 是否展开更多信息
      genderOptions: ['请选择', '男', '女'],
      formData: {
        name: '',
        nickname: '',
        gender: null,
        homeAddress: '',
        relationshipId: null,
        relationshipName: '',
        phoneNumber: '',
        phoneNumber2: '',
        email: '',
        birthday: '',
        birthdayType: 1, // 默认使用公历
        birthplace: '',
        avatarUrl: '',
        mailingAddress: '',
        work: '',
        school: '',
        companyName: '',
        remark: '',
        contactTags: [], // 修改为数组，只存储标签ID
      },
      // 标签数据 - 按类型分类，用于展示
      tagData: {
        LIKE: [], // 爱好标签列表
        NOTLIKE: [], // 讨厌标签列表
        EAT: [], // 口味标签列表
        HABIT: [], // 习惯标签列表
        SKILL: [] // 技能标签列表
      },
      // 新增：用于存储按类型分类的标签ID
      tagIdsByType: {
        LIKE: [], // 爱好标签ID
        NOTLIKE: [], // 讨厌标签ID
        EAT: [], // 口味标签ID
        HABIT: [], // 习惯标签ID
        SKILL: [] // 技能标签ID
      }
    }
  },
  
  onLoad(options) {
    // 获取状态栏高度
    const sysInfo = uni.getSystemInfoSync()
    this.statusBarHeight = sysInfo.statusBarHeight
    
    // 判断是新增还是编辑
    if (options.id) {
      this.isEdit = true
      this.contactId = options.id
      this.fetchContactDetail()
      
      // 加载标签数据
      this.loadTagData()
    }
  },
  
  // 添加onShow生命周期函数
  onShow() {
    // 检查是否有通过本地存储传递的标签数据
    try {
      const needUpdateTags = uni.getStorageSync('needUpdateTags');
      if (needUpdateTags) {
        console.log('从本地存储获取标签数据:', needUpdateTags);
        this.updateTags(needUpdateTags.type, needUpdateTags.tags);
        // 使用后清除数据
        uni.removeStorageSync('needUpdateTags');
      }
    } catch (e) {
      console.error('获取本地存储标签数据失败:', e);
    }
    
    // 检查是否有关系类型选择数据
    try {
      const selectedRelationship = uni.getStorageSync('selectedRelationshipType');
      if (selectedRelationship) {
        console.log('检测到关系类型选择:', selectedRelationship);
        
        // 判断selectedRelationship是对象还是字符串
        if (typeof selectedRelationship === 'object') {
          // 新的格式：对象，包含id、name和icon
          this.formData.relationshipId = selectedRelationship.id;
          this.formData.relationshipName = selectedRelationship.name;
        } else {
          // 旧的格式：只有类型名称的字符串
          this.formData.relationshipName = selectedRelationship;
          // 注意：这种情况下没有设置relationshipId，可能需要通过名称查找ID
        }
        
        // 使用后清除
        uni.removeStorageSync('selectedRelationshipType');
      }
    } catch (e) {
      console.error('获取关系类型选择数据失败:', e);
    }
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 切换展开/收起状态
    toggleExpand() {
      this.expanded = !this.expanded
    },
    
    // 添加选择关系方法
    selectRelationship() {
      uni.navigateTo({
        url: '/pages/comm/type-manage?businType=RELATIONSHIP&pageTitle=选择关系类型'
      });
    },
    
    // 加载标签数据
    async loadTagData() {
      try {
        // 一次性加载所有类型标签数据
        const tagTypes = ['LIKE', 'NOTLIKE', 'EAT', 'HABIT', 'SKILL'];
        const res = await TagApi.queryContactTag({
          contactId: this.contactId,
          tagType: tagTypes.join(',') // 使用逗号分隔多个标签类型
        });
        
        if (res.code === 0 && res.data) {
          // 处理返回的数据，按类型分类
          tagTypes.forEach(type => {
            this.tagData[type] = res.data.filter(tag => tag.tagType === type) || [];
          });
        }
      } catch (error) {
        console.error('加载标签数据失败', error);
      }
    },
    
    // 获取已选择的标签（包含颜色信息）
    getSelectedTags(tagType) {
      if (!this.tagIdsByType[tagType] || this.tagIdsByType[tagType].length === 0) {
        return [];
      }
      
      // 从tagData中查找对应的标签内容
      const tagIds = this.tagIdsByType[tagType];
      
      // 确保tagData[tagType]存在且是数组
      if (!this.tagData[tagType] || !Array.isArray(this.tagData[tagType])) {
        return [];
      }
      
      return this.tagData[tagType]
        .filter(tag => {
          // 始终使用tagId作为标识符
          return tagIds.includes(tag.tagId);
        })
        .map(tag => ({
          tagName: tag.tagName,
          color: tag.color || this.getDefaultColor(tagType)
        }));
    },
    
    // 获取默认颜色
    getDefaultColor(tagType) {
      const colorMap = {
        LIKE: '#FF6B6B',
        NOTLIKE: '#FF5252',
        EAT: '#FF9800',
        HABIT: '#9C27B0',
        SKILL: '#4CAF50'
      };
      return colorMap[tagType] || '#CCCCCC';
    },

    // 修改获取联系人详情方法中处理标签的部分
    async fetchContactDetail() {
      try {
        const res = await ContactApi.queryContactDetail({ id: this.contactId });
        if (res.code === 0 && res.data) {
          const detail = res.data;
          
          // 填充表单数据
          this.formData.name = detail.name || ''
          this.formData.nickname = detail.nickname || ''
          this.formData.gender = detail.gender
          this.formData.homeAddress = detail.homeAddress || ''
          this.formData.relationshipId = detail.relationshipId
          this.formData.relationshipName = detail.relationshipName || ''
          this.formData.phoneNumber = detail.phoneNumber || ''
          this.formData.phoneNumber2 = detail.phoneNumber2 || ''
          this.formData.email = detail.email || ''
          this.formData.avatarUrl = detail.avatarUrl || ''
          this.formData.mailingAddress = detail.mailingAddress || ''
          this.formData.birthdayType = detail.birthdayType || 1
          
          // 处理生日信息
          if (detail.birthday) {
            const date = new Date(detail.birthday)
            this.formData.birthday = this.formatDate(date)
          }
          
          this.formData.birthplace = detail.birthplace || ''
          this.formData.school = detail.school || ''
          this.formData.companyName = detail.companyName || ''
          this.formData.work = detail.work || ''
          this.formData.remark = detail.remark || ''
          
          // 处理标签数据 - 修改字段名为contactTagInfos
          if (detail.contactTagInfos && typeof detail.contactTagInfos === 'object') {
            // 重置标签数据
            this.formData.contactTags = []
            
            // 清空所有类型的标签ID
            Object.keys(this.tagIdsByType).forEach(type => {
              this.tagIdsByType[type] = []
            })
            
            // 遍历每种类型的标签
            Object.keys(detail.contactTagInfos).forEach(tagType => {
              const tags = detail.contactTagInfos[tagType]
              if (Array.isArray(tags) && tags.length > 0) {
                // 更新tagData，确保数据结构一致，始终使用tagId作为标识符
                this.tagData[tagType] = tags.map(tag => ({
                  id: tag.id, // 保留关系ID
                  tagId: tag.tagId, // 标签ID
                  tagType: tag.tagType,
                  tagName: tag.tagName,
                  color: tag.color // 添加颜色信息
                }))
                
                // 提取标签ID并更新tagIdsByType，使用tagId
                this.tagIdsByType[tagType] = tags.map(tag => tag.tagId)
                
                // 将标签ID添加到contactTags数组，使用tagId
                this.formData.contactTags.push(...tags.map(tag => tag.tagId))
              }
            })
          }
        }
      } catch (error) {
        console.error('获取联系人详情失败', error);
        uni.showToast({
          title: '获取联系人信息失败',
          icon: 'none'
        });
      }
    },

    // 新增：按类型分类标签
    classifyTagsByType(tags) {
      // 重置所有类型的标签ID
      Object.keys(this.tagIdsByType).forEach(type => {
        this.tagIdsByType[type] = [];
      });
      
      // 遍历所有标签，按类型分类
      tags.forEach(tag => {
        const tagObj = typeof tag === 'object' ? tag : this.findTagById(tag);
        if (tagObj && tagObj.tagType) {
          this.tagIdsByType[tagObj.tagType].push(tagObj.id);
        }
      });
    },

    // 新增：根据ID查找标签
    findTagById(tagId) {
      for (const type in this.tagData) {
        const found = this.tagData[type].find(tag => tag.id === tagId);
        if (found) return found;
      }
      return null;
    },

    // 修改更新标签数据方法
    updateTags(type, tags) {
      console.log('接收到标签更新:', type, tags);
      
      // 更新对应类型的标签ID
      this.tagIdsByType[type] = tags.map(tag => {
        // 始终使用tagId作为标识符
        return typeof tag === 'object' ? tag.tagId : tag;
      });
      
      // 更新tagData，用于显示
      this.tagData[type] = tags;
      
      // 更新formData.contactTags，合并所有类型的标签ID
      this.formData.contactTags = [];
      Object.values(this.tagIdsByType).forEach(ids => {
        this.formData.contactTags.push(...ids);
      });
      
      // 去重
      this.formData.contactTags = [...new Set(this.formData.contactTags)];
    },

    // 修改保存联系人方法
    async saveContact() {
      // 表单验证
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入姓名',
          icon: 'none'
        });
        return;
      }
      
      // 构建保存数据
      const saveData = {
        name: this.formData.name,
        nickname: this.formData.nickname || '',
        gender: this.formData.gender,
        homeAddress: this.formData.homeAddress,
        relationshipId: this.formData.relationshipId,
        phoneNumber: this.formData.phoneNumber || '',
        phoneNumber2: this.formData.phoneNumber2 || '',
        email: this.formData.email || '',
        birthday: this.formData.birthday ? this.formatBirthdayForSave(this.formData.birthday) : null,
        birthdayType: this.formData.birthdayType,
        school: this.formData.school || '',
        companyName: this.formData.companyName || '',
        work: this.formData.work || '',
        mailingAddress: this.formData.mailingAddress || '',
        remark: this.formData.remark || '',
        contactTagIds: this.formData.contactTags,
        avatarUrl: this.formData.avatarUrl || ''
      };
      
      try {
        uni.showLoading({
          title: '保存中...'
        })
        
        if (this.isEdit) {
          // 编辑联系人，确保id为数字类型
          saveData.id = parseInt(this.contactId)
        }
        
        // 调用添加或更新接口
        const res = await ContactApi.addOrUpdateContact(saveData)
        
        if (res.code === 0) {
          uni.showToast({
            title: this.isEdit ? '更新成功' : '添加成功',
            icon: 'success'
          })
          
          // 设置全局标记，表示联系人数据已更新
          getApp().globalData.contactDataUpdated = true;
          
          // 返回上一页并刷新列表
          setTimeout(() => {
            // 保留现有的刷新逻辑，以确保兼容性
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            
            // 如果上一页是联系人列表，刷新列表
            if (prevPage) {
              // 联系人列表页面
              if (prevPage.fetchContactList) {
                prevPage.fetchContactList()
              }
              
              // 联系人详情页面
              if (prevPage.fetchContactDetail) {
                prevPage.fetchContactDetail()
              }
              
              // 联系人资料标签页
              if (prevPage.refreshData) {
                prevPage.refreshData()
              }
            }
            
            uni.navigateBack()
          }, 500)
        } else {
          uni.showToast({
            title: res.msg || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存联系人失败', error)
        uni.showToast({
          title: '网络异常，请稍后重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 性别选择
    onGenderChange(e) {
      this.formData.gender = parseInt(e.detail.value)
    },
    
    // 添加生日选择方法
    onBirthdayChange(e) {
      this.formData.birthday = e.detail.value;
    },
    
    // 格式化日期
    formatDate(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 显示标签选择页面
    showTagSelect(tagType) {
      uni.navigateTo({
        url: `/pages/contact/tag-select?type=${tagType}&contactId=${this.contactId || 0}`,
        events: {
          // 接收标签选择页面返回的数据
          updateTags: (type, tags) => {
            this.updateTags(type, tags);
          }
        },
        success: (res) => {
          // 向标签选择页面传递已选标签ID
          res.eventChannel.emit('selectedTags', {
            tags: this.tagIdsByType[tagType] || []
          });
        }
      });
    },
    
    // 上传头像
    uploadAvatar() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: async (res) => {
          const tempFilePath = res.tempFilePaths[0];
          
          // 使用FileApi上传文件
          const result = await FileApi.uploadFile(tempFilePath);
          if (result && result.data) {
            this.formData.avatarUrl = result.data;
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          }
        }
      });
    },
    
    // 格式化生日为保存时需要的yyyy-MM-dd格式
    formatBirthdayForSave(birthdayStr) {
      // 如果已经是yyyy-MM-dd格式，直接返回
      if (birthdayStr.includes('-')) {
        return birthdayStr;
      }
      
      // 如果是yyyyMMdd格式，转换为yyyy-MM-dd
      if (birthdayStr.length === 8) {
        const year = birthdayStr.substring(0, 4);
        const month = birthdayStr.substring(4, 6);
        const day = birthdayStr.substring(6, 8);
        return `${year}-${month}-${day}`;
      }
      
      return birthdayStr;
    },
    
    // 新增方法：将yyyyMMdd格式的日期字符串转换为时间戳
    parseDateToTimestamp(dateStr) {
      if (!dateStr || dateStr.length !== 8) return null;
      
      const year = parseInt(dateStr.substring(0, 4));
      const month = parseInt(dateStr.substring(4, 6)) - 1; // 月份从0开始
      const day = parseInt(dateStr.substring(6, 8));
      
      const date = new Date(year, month, day);
      return date.getTime();
    }
  }  // 添加这个右大括号来结束methods对象
}  // 这个右大括号结束export default对象
</script>

<style lang="scss">
@import '@/static/styles/contact-edit.scss';

/* 添加底部保存按钮样式 */
.bottom-save-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #2196F3;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  
  /* 圆弧形样式 */
  border-radius: 45rpx;
  
  /* 适配底部安全区域 */
  margin-bottom: env(safe-area-inset-bottom);
}

/* 修改表单容器样式，移除顶部内边距 */
.form-container {
  height: calc(100vh - 44px - var(--status-bar-height));
  padding-top: 0;
  box-sizing: border-box;
}

/* 移除自定义导航栏相关样式 */
.custom-navbar {
  display: none;
}
</style>